// 健康检查路由

const express = require('express');
const router = express.Router();
const { logger } = require('../../config/monitoring');

// 健康检查状态
let healthStatus = {
  status: 'healthy',
  timestamp: new Date().toISOString(),
  uptime: process.uptime(),
  version: process.env.npm_package_version || '1.0.0',
  environment: process.env.NODE_ENV || 'production',
  checks: {}
};

// 检查数据库连接
async function checkDatabase() {
  try {
    // 这里应该导入实际的数据库连接
    // const db = require('../config/database');
    // await db.authenticate();
    
    return {
      status: 'healthy',
      responseTime: Date.now(),
      message: 'Database connection successful'
    };
  } catch (error) {
    logger.error('Database health check failed:', error);
    return {
      status: 'unhealthy',
      responseTime: Date.now(),
      message: error.message
    };
  }
}

// 检查Redis连接
async function checkRedis() {
  try {
    // 这里应该导入实际的Redis连接
    // const redis = require('../config/redis');
    // await redis.ping();
    
    return {
      status: 'healthy',
      responseTime: Date.now(),
      message: 'Redis connection successful'
    };
  } catch (error) {
    logger.error('Redis health check failed:', error);
    return {
      status: 'unhealthy',
      responseTime: Date.now(),
      message: error.message
    };
  }
}

// 检查内存使用
function checkMemory() {
  const memUsage = process.memoryUsage();
  const totalMem = require('os').totalmem();
  const freeMem = require('os').freemem();
  const usedMem = totalMem - freeMem;
  const memoryUsagePercent = (usedMem / totalMem) * 100;
  
  const status = memoryUsagePercent > 85 ? 'unhealthy' : 'healthy';
  
  return {
    status,
    responseTime: Date.now(),
    message: `Memory usage: ${memoryUsagePercent.toFixed(2)}%`,
    details: {
      rss: memUsage.rss,
      heapTotal: memUsage.heapTotal,
      heapUsed: memUsage.heapUsed,
      external: memUsage.external,
      systemTotal: totalMem,
      systemFree: freeMem,
      systemUsed: usedMem,
      usagePercent: memoryUsagePercent
    }
  };
}

// 检查磁盘空间
function checkDisk() {
  try {
    const fs = require('fs');
    const stats = fs.statSync('.');
    
    // 简化的磁盘检查，实际应该使用更准确的方法
    return {
      status: 'healthy',
      responseTime: Date.now(),
      message: 'Disk space sufficient'
    };
  } catch (error) {
    logger.error('Disk health check failed:', error);
    return {
      status: 'unhealthy',
      responseTime: Date.now(),
      message: error.message
    };
  }
}

// 检查外部服务
async function checkExternalServices() {
  const checks = {};
  
  // 检查OSS服务
  try {
    // 这里应该实际测试OSS连接
    checks.oss = {
      status: 'healthy',
      responseTime: Date.now(),
      message: 'OSS service available'
    };
  } catch (error) {
    checks.oss = {
      status: 'unhealthy',
      responseTime: Date.now(),
      message: error.message
    };
  }
  
  // 检查微信API
  try {
    // 这里应该实际测试微信API
    checks.wechat = {
      status: 'healthy',
      responseTime: Date.now(),
      message: 'WeChat API available'
    };
  } catch (error) {
    checks.wechat = {
      status: 'unhealthy',
      responseTime: Date.now(),
      message: error.message
    };
  }
  
  return checks;
}

// 简单健康检查
router.get('/', (req, res) => {
  const simpleHealth = {
    status: 'healthy',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    version: process.env.npm_package_version || '1.0.0'
  };
  
  res.status(200).json(simpleHealth);
});

// 详细健康检查
router.get('/detailed', async (req, res) => {
  try {
    const startTime = Date.now();
    
    // 并行执行所有检查
    const [
      databaseCheck,
      redisCheck,
      memoryCheck,
      diskCheck,
      externalChecks
    ] = await Promise.all([
      checkDatabase(),
      checkRedis(),
      checkMemory(),
      checkDisk(),
      checkExternalServices()
    ]);
    
    const checks = {
      database: databaseCheck,
      redis: redisCheck,
      memory: memoryCheck,
      disk: diskCheck,
      ...externalChecks
    };
    
    // 确定整体健康状态
    const overallStatus = Object.values(checks).every(check => 
      check.status === 'healthy'
    ) ? 'healthy' : 'unhealthy';
    
    const healthReport = {
      status: overallStatus,
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      version: process.env.npm_package_version || '1.0.0',
      environment: process.env.NODE_ENV || 'production',
      responseTime: Date.now() - startTime,
      checks
    };
    
    // 更新全局健康状态
    healthStatus = healthReport;
    
    const statusCode = overallStatus === 'healthy' ? 200 : 503;
    res.status(statusCode).json(healthReport);
    
  } catch (error) {
    logger.error('Health check failed:', error);
    
    const errorResponse = {
      status: 'unhealthy',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      version: process.env.npm_package_version || '1.0.0',
      environment: process.env.NODE_ENV || 'production',
      error: error.message
    };
    
    res.status(503).json(errorResponse);
  }
});

// 就绪检查（用于Kubernetes等容器编排）
router.get('/ready', async (req, res) => {
  try {
    // 检查关键服务
    const databaseCheck = await checkDatabase();
    const redisCheck = await checkRedis();
    
    const isReady = databaseCheck.status === 'healthy' && 
                   redisCheck.status === 'healthy';
    
    const readyResponse = {
      ready: isReady,
      timestamp: new Date().toISOString(),
      checks: {
        database: databaseCheck,
        redis: redisCheck
      }
    };
    
    const statusCode = isReady ? 200 : 503;
    res.status(statusCode).json(readyResponse);
    
  } catch (error) {
    logger.error('Readiness check failed:', error);
    res.status(503).json({
      ready: false,
      timestamp: new Date().toISOString(),
      error: error.message
    });
  }
});

// 存活检查（用于Kubernetes等容器编排）
router.get('/live', (req, res) => {
  // 简单的存活检查，只要进程在运行就返回成功
  res.status(200).json({
    alive: true,
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    pid: process.pid
  });
});

module.exports = router;